package org.zjframework.traceframe.common.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import org.zjframework.traceframe.common.util.StringEscapeEditor;
import com.alibaba.fastjson.JSON;
import static org.zjframework.traceframe.common.util.ContextHolderUtils.getRequest;
import static org.zjframework.traceframe.common.util.ContextHolderUtils.getSession;


/**
 * 基础控制器，其他控制器需集成此控制器获得initBinder自动转换的功能
 *
 *
 */
@Controller
@RequestMapping("/baseController")
public class BaseController {

	@InitBinder
	public void initBinder(ServletRequestDataBinder binder) {
		//StringEscapeUtils.escapeSql()
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
		binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false,true));
	}


	/**
	 * @author 赵继
	 * 使用fastJson返回json
	 */
	public void writeJSON(Object object,HttpServletRequest request,HttpServletResponse response){
		try {
			String json = JSON.toJSONStringWithDateFormat(object, "yyyy-MM-dd HH:mm:ss");
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().write(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

//	protected boolean isValidCsrfHeaderToken() {
//		if (getRequest().getHeader("__RequestVerificationToken") == null
//				|| getSession()
//				.getAttribute(CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME) == null
//				|| !getRequest()
//				.getHeader("__RequestVerificationToken")
//				.equals(getSession()
//						.getAttribute(
//								CSRFTokenManager.CSRF_TOKEN_FOR_SESSION_ATTR_NAME)
//						.toString())) {
//			return false;
//		}
//		return true;
//	}

}
